// pages/createCode/createCode.js
const API = require('../../utils/api.js')
const util = require('../../utils/util.js')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productImageUrl: '',
    colors: ['黑色','黄色','紫色','青色','蓝色','红色','绿色','洋红色'],//可选的编码颜色
    colorIndex: 0,//选中颜色的index
    showMoreSetting: false,//是否显示更多关于编码图片的配置项，默认不显示
    imageWidth: 405,//生成图片的宽度，单位毫米，默认405
    imageHeight: 281,//生成图片的高度，单位毫米，默认281
    dpi: 300,//图片dpi，默认300
    imageOffset: [5,5,5,5],//生成图片的边距，分别为上边距、下边距、左边距、右边距
    numbers: [1,2,3,4,5,6,7,8,9,10],//可选的批量生成数量
    numberIndex: 0,//批量生成点阵图的数量，默认1，最大10
    codeIncrease:0,//批量生成时编码的增加量，默认0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 点击更多与收起的方法
   */
  tapMore:function() {
    this.setData({
      showMoreSetting: !this.data.showMoreSetting
    })
  },

  /**
   * 上传产品图，返回图片url
   */
  uploadImage:function() {
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        wx.showLoading({
          title: '上传中'
        })
        wx.uploadFile({
          filePath: res.tempFilePaths[0],
          name: 'productImage',
          url: API.Upload.productImage,
          success (res) {
            wx.hideLoading()
            let result = JSON.parse(res.data)
            if(result.code == "SUCCESS"){
              util.showSuccessToast(result.message, 1500)
              that.setData({
                productImageUrl: result.data
              })
            }else{
              util.showErrorMessage(result.message)
            }
          },
          fail() {
            wx.hideLoading()
            util.showNetworkError()
          }
        })
      }
    })
  },

  /**
   * 查看已上传的产品图
   */
  viewImage: function() {
    wx.navigateTo({
      url: '/pages/webview/webview?url=' + this.data.productImageUrl,
    })
  },

  /**
   * 响应编码颜色的改变
   */
  bindColorChange: function(e) {
    this.setData({
      colorIndex: e.detail.value
    })
  },

  /**
   * 响应批量生成数量的改变
   */
  bindNumChange: function(e) {
    this.setData({
      numberIndex: e.detail.value
    })
  },

  /**
   * 响应更多设置中各输入框的改变
   */
  inputImageParam: function(e) {
    let type = e.currentTarget.dataset.type
    if(type == "imageWidth") {
      this.setData({
        imageWidth: e.detail.value
      })
    } else if(type == "imageHeight") {
      this.setData({
        imageHeight: e.detail.value
      })
    } else if(type == "imageOffsetTop") {
      this.data.imageOffset[0] = e.detail.value
      this.setData({
        imageOffset: this.data.imageOffset
      })
    } else if(type == "imageOffsetBottom") {
      this.data.imageOffset[1] = e.detail.value
      this.setData({
        imageOffset: this.data.imageOffset
      })
    } else if(type == "imageOffsetLeft") {
      this.data.imageOffset[2] = e.detail.value
      this.setData({
        imageOffset: this.data.imageOffset
      })
    } else if(type == "imageOffsetRight") {
      this.data.imageOffset[3] = e.detail.value
      this.setData({
        imageOffset: this.data.imageOffset
      })
    } else if(type == "imageDPI") {
      this.setData({
        dpi: e.detail.value
      })
    } else if(type == "codeIncrease") {
      this.setData({
        codeIncrease: e.detail.value
      })
    }
  },

  /**
   * 点击确定按钮
   */
  formSubmit: function(e) {
    let that = this
    let submitInfo = this.generateSubmitInfo(e.detail.value)
    if(!this.checkSubmitInfo(submitInfo)){
      return
    }
    wx.showLoading({
      title: '生成中',
    })
    wx.request({
      url:  API.Product.createCode,
      method: 'POST',
      data: {
        "submitInfo": submitInfo
      },
      success(res) {
        wx.hideLoading()
        if(res.data.code == "SUCCESS") {
          wx.showModal({
            content: res.data.message,
            cancelText: "复制链接",
            confirmText: "直接下载",
            success(modalRes) {
              if(modalRes.confirm) {
                wx.downloadFile({
                  url: res.data.data,
                  header: {
                    "Content-Type": "application/zip",
                  },
                  success (downloadRes) {
                    if(downloadRes.statusCode == 200) {
                      wx.saveFile({
                        tempFilePath: downloadRes.tempFilePath,
                        success (resource) {
                          util.showTips("文件已下载到"+resource.savedFilePath,5000)
                        }
                      })
                    }
                  }
                })
              } else if (modalRes.cancel) {
                wx.setClipboardData({
                  data: res.data.data,
                })
              }
            }
          })
        } else {
          util.showErrorMessage(res.data.message)
        }
      },
      fail() {
        wx.hideLoading()
        util.showNetworkError()
      }
    })
  },

  generateSubmitInfo: function(submitData) {
    let that = this
    let submitInfo = {
      producer_id: app.globalData.userinfo.id,
      productName: submitData.productName,
      productImageUrl: that.data.productImageUrl,
      code: submitData.code,
      color: that.data.colors[submitData.colorIndex],
      imageWidth: submitData.imageWidth || that.data.imageWidth,
      imageHeight: submitData.imageHeight || that.data.imageHeight,
      imageOffsetTop: submitData.imageOffsetTop || that.data.imageOffset[0],
      imageOffsetBottom: submitData.imageOffsetBottom || that.data.imageOffset[1],
      imageOffsetLeft: submitData.imageOffsetLeft || that.data.imageOffset[2],
      imageOffsetRight: submitData.imageOffsetRight || that.data.imageOffset[3],
      imageDPI: submitData.imageDPI || that.data.dpi,
      imageNum: that.data.numbers[that.data.numberIndex],
      codeIncrease: submitData.codeIncrease || that.data.codeIncrease,
      code_space: 10
    }
    return submitInfo
  },

  checkSubmitInfo: function(submitInfo) {
    if(submitInfo.productName == "") {
      util.showTips("请输入产品名", 1500)
      return false
    }else if(submitInfo.productImageUrl == "") {
      util.showTips("请上传产品图", 1500)
      return false
    }else if(submitInfo.imageNum != 1 && submitInfo.codeIncrease <= 0){
      util.showTips("编码递增有误",1500)
      return false
    }else {
      return true
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})